/**
* @program: src
*
* @description:判断请求ID是否存在
*
* @author: Mr.chen
*
* @create: 2020-11-04 15:07
**/
package wstoken
import (
	"ydd-im/util/response"
	"errors"
	"github.com/gin-gonic/gin"

	"net/http"
)

func SetUp() gin.HandlerFunc {
	return func(c *gin.Context) {
		err := verifyRequest(c)
		if err != nil {
			response.ResponseJsonFail(c,response.Response{
				Code:response.ErrorCode,
				Message:err.Error(),
			})
			c.Abort()
			return
		}
		c.Next()
	}
}
func verifyRequest(c *gin.Context)  error {
	if c.Request.Method != http.MethodPost {
		return errors.New("请求方法有误")
	}
	headers :=c.Request.Header
	requestId := headers.Get("RequestId")
	//检查header是否设置requestId
	if len(requestId) == 0 {
		return  errors.New( "系统ID不能为空")
	}
	//判断是否被注册
	resp, err := etcd.Get(define.ETCD_PREFIX_ACCOUNT_INFO + requestId)
	if err != nil {
		return  errors.New( "etcd服务器错误")
	}
	if resp.Count == 0 {
		return  errors.New( "系统ID无效")
	}
	return nil
	//requestId := c.Request.Header.Get("X-Request-Id")
	//if requestId == "" {
	//	requestId = uuid.GenUUID()
	//}
	//c.Set("X-Request-Id", requestId)
	//c.Writer.Header().Set("X-Request-Id", requestId)
	//c.Next()
}